package com.xinz.protocal;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import com.xinz.serialization.IndexMap;

public class NativeInterfaceProvider {

	IndexMap<Object, Method> methodTable = new IndexMap<Object, Method>();
	
	Set<Class<?>> registedInterface = new HashSet<Class<?>>();
	
	/**
	 * 给接口绑定具体的本地实现，以供远程调用
	 * @param interfaceClass
	 * @param implementClass
	 */
	public void addInterface(Class<?> interfaceClass) {
		assert interfaceClass.isInterface() : "这货不是接口：" + interfaceClass;
		// 避免重复添加
		if(registedInterface.add(interfaceClass)) {
			for(Method method : interfaceClass.getMethods()) {
				methodTable.put(getMethodKey(method), method);
			}
		}
	}
	
	public Object getMethodKey(Method method) {
		return getMethodKey(method.getDeclaringClass().getName(), method.getName());
	}
	
	public Object getMethodKey(String interfaceName, String method) {
		return interfaceName + ":" + method;
	}
	
	public Method getMethod(Object key) {
		return methodTable.get(key);
	}
	
	public int getMethodIndex(String interfaceName, String methodName) {
		return methodTable.indexOfKey(getMethodKey(interfaceName, methodName));
	}
	
	public Method getMethodAt(int index) {
		return methodTable.valueAt(index);
	}
}
